﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eShop.Business;
using eShop.Model;
using eShop.Utility;
using System.Web.Script.Serialization;

public partial class admin_controls_product_form : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindFormDataToUI();
            BindModelToUI();
        }
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                SaveProduct();
                uccResponseMessage.SetSuccessMessage("Data saved successfully");
                uccResponseMessage.Visible = true;
            }
        }
        catch (Exception exception)
        {
            uccResponseMessage.SetFailMessage("Failed to save data." + "<br />" + exception.Message);
            uccResponseMessage.Visible = true;
        }
        finally
        {
            BindModelToUI();
        }
    }

    private void BindFormDataToUI()
    {
        ddlCategory.DataSource = CategoryManager.GetAllFormatedActiveCategoriesWithSubCategory();
        ddlCategory.DataTextField = "Value";
        ddlCategory.DataValueField = "Key";
        ddlCategory.DataBind();

        ddlManufacturer.DataSource = ManufacturerManager.GetAllManufacturers();
        ddlManufacturer.DataValueField="ProductBrandId";
        ddlManufacturer.DataTextField = "BrandName";
        ddlManufacturer.DataBind();
    }

    private void BindModelToUI()
    {
        if (Id > 0)
        {
            Product product = LoadProduct();
            BindProductToUI(product);
        }
        else
        {
            ClearUI();
        }
    }

    private void ClearUI()
    {
        tbxProductName.Text = string.Empty;
        tbxItemNumber.Text = string.Empty;
        tbxDisplayOrder.Text = string.Empty;
        ckeditorDescription.Text = string.Empty;
        ckeditorSpecification.Text = string.Empty;
        tbRetailPrice.Text = string.Empty;
        tbxPrice.Text = string.Empty;
        tbSpecialPrice.Text = string.Empty;
        gvStock.DataSource = new List<ProductStock>();
        gvStock.DataBind();
        cbxIsActive.Checked = false;
        cbxIsFeatured.Checked = false;
        cbxIsNew.Checked = false;
        cbxIsSale.Checked = false;

        ddlCategory.SelectedIndex = 0;
        ddlManufacturer.SelectedIndex = 0;
    }

    private void BindProductToUI(Product product)
    {
        tbxProductName.Text = product.ProductName;
        tbxItemNumber.Text = product.ItemNumber;
        ddlCategory.SelectedValue = product.CategoryId.ToString();
        ddlManufacturer.SelectedValue = product.BrandId.ToString();
        tbxDisplayOrder.Text = product.DisplayOrder;
        tbRetailPrice.Text = product.RetailPrice.ToString();
        tbxPrice.Text = product.ProductPrice.ToString();
        tbSpecialPrice.Text = product.ClearencePrice.ToString();
        cbxIsFeatured.Checked = product.IsFeatured;
        cbxIsNew.Checked = product.IsNewArrival;
        cbxIsSale.Checked = product.IsClearenceItem;
        cbxIsActive.Checked = product.IsActive;

        ckeditorDescription.Text= product.ProductDescription;
         ckeditorSpecification.Text = product.Specification;

        if (!string.IsNullOrEmpty(product.ProductImageUrl))
        {
            imgProductDefaultImagePreview.ImageUrl = product.ProductImageLargeThumbnail;
            imgProductDefaultImagePreview.Visible = true;
        }

        gvStock.DataSource = product.Stocks;
        gvStock.DataBind();

        rptAdditionalPreview.DataSource = product.AdditionalImages;
        rptAdditionalPreview.DataBind();
        rptAdditionalPreview.Visible = (product.AdditionalImages != null && product.AdditionalImages.Count > 0);
    }

    private Product LoadProduct()
    {
        if (Id > 0)
        {
            return ProductManager.GetProductById(Id);
        }
        else
        {
            return new Product();
        }
    }

    private void SaveProduct()
    {
        Product product = LoadProduct();
        product.ProductName = tbxProductName.Text.Trim();
        product.ItemNumber = tbxItemNumber.Text.Trim();
        product.CategoryId = Convert.ToInt32(ddlCategory.SelectedValue);
        product.BrandId = Convert.ToInt32(ddlManufacturer.SelectedValue);
        product.DisplayOrder = tbxDisplayOrder.Text.Trim();
        product.ProductPrice = Convert.ToDouble(tbxPrice.Text.Trim());
        product.RetailPrice = Convert.ToDouble(tbRetailPrice.Text.Trim());
        if (!string.IsNullOrEmpty(tbSpecialPrice.Text))
            product.ClearencePrice = Convert.ToDouble(tbSpecialPrice.Text.Trim());
        if (!string.IsNullOrEmpty(tbSpecialPrice.Text))
        {
            product.ClearencePrice = Convert.ToDouble(tbSpecialPrice.Text);
        }
        product.IsFeatured = cbxIsFeatured.Checked;
        product.IsNewArrival = cbxIsNew.Checked;
        product.IsClearenceItem = cbxIsSale.Checked;
        product.IsActive = cbxIsActive.Checked;
        product.ProductDescription = ckeditorDescription.Text.Trim();
        product.Specification = ckeditorSpecification.Text.Trim();
        if (fluProductDefaultImage.HasFile)
        {
            product.ProductImageUrl = WebPresentationUtility.UploadImageAndValidate(ApplicationSettings.TemporaryFolderPath, fluProductDefaultImage.PostedFile);
        }

        product.Stocks.AddRange(GetNewProductStock());

        List<ProductImage> additionalImages = GetAdditionalImages();
        if (product.ProductId > 0)
        {
            ProductManager.UpdateProduct(product, additionalImages);
        }
        else
        {
            ProductManager.CreateProduct(product, additionalImages);
        }
    }

    private Int32? _id;
    private Int32 Id
    {
        get
        {
            if (!_id.HasValue)
            {
                try
                {
                    if (HttpContext.Current.Request.QueryString != null && !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["pid"]))
                    {
                        _id = Convert.ToInt32(HttpContext.Current.Request.QueryString["pid"]);
                    }
                    else
                    {
                        _id = -1;
                    }
                }
                catch
                {
                    _id = -1;
                }
            }
            return _id.Value;
        }
    }

    private List<ProductImage> GetAdditionalImages()
    {
        List<ProductImage> additionalImages = new List<ProductImage>();
        for (int i = 1; i < Request.Files.Count; i++)
        {
            HttpPostedFile fuImageAdditional = Request.Files[i];
            if (Request.Files[i].ContentLength > 0)
            {
                ProductImage productImage = new ProductImage();
                productImage.AdditionalImageUrl = WebPresentationUtility.UploadImageAndValidate(ApplicationSettings.TemporaryFolderPath, fuImageAdditional);
                additionalImages.Add(productImage);
            }
        }
        return additionalImages;
    }

    private List<ProductStock> GetNewProductStock()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        List<ProductStockViewObject> productStockViewObjects = js.Deserialize<List<ProductStockViewObject>>(hStockDescription.Value);

        List<ProductStock> productStocks = new List<ProductStock>();
        foreach (ProductStockViewObject productStockViewObject in productStockViewObjects)
        {
            ProductStock productStock = new ProductStock();
            productStock.Description = productStockViewObject.Description;
            productStock.Weight = (double)productStockViewObject.Weight;
            productStock.StockAvailable = productStockViewObject.Quantity;
            productStock.StockAlertCount = productStockViewObject.AlertLevel;
            productStocks.Add(productStock);
        }
        return productStocks;
    }

    protected void gvStock_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow gridViewRow = (GridViewRow)((Button)e.CommandSource).Parent.Parent;
        int rowIndex = gridViewRow.RowIndex;
        int stockId = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "StockUpdate")
        {
            ProductStock productStock = ProductStockManager.GetStockById(stockId);
            productStock.Description = ((TextBox)gridViewRow.FindControl("tbDescription")).Text.Trim();
            productStock.Weight = Convert.ToDouble(((TextBox)gridViewRow.FindControl("tbWeight")).Text.Trim());
            productStock.StockAvailable = Convert.ToInt32(((TextBox)gridViewRow.FindControl("tbQuantity")).Text.Trim());
            productStock.StockAlertCount = Convert.ToInt32(((TextBox)gridViewRow.FindControl("tbStockAlert")).Text.Trim());
            ProductStockManager.Update(productStock);
            BindModelToUI();
        }
        else if (e.CommandName == "StockRemove")
        {
            ProductStockManager.Delete(stockId);
            BindModelToUI();
        }
    }

    protected void rptAdditionalPreview_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "DeleteImage")
        {
            ProductManager.DeleteAdditionalImage(Convert.ToInt32(e.CommandArgument));
            BindModelToUI();
        }
    }

    class ProductStockViewObject
    {
        public string Description;
        public float Weight;
        public int Quantity;
        public int AlertLevel;
    }
}